import 'package:dio/dio.dart';
import 'package:loxen/api/dio_setting.dart';
import 'package:loxen/mode/login_bean.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/save_util.dart';

class AuthInterceptor extends Interceptor {
  @override
  Future onRequest(RequestOptions options) async {
    String accessToken = await SharedPreferencesUtil.getData(Constants.ACCESS_TOKEN);
    if (accessToken != null && accessToken != '') {
      options.headers['content-type'] = 'application/json;charset=utf-8';
      options.headers['Authorization'] = 'JWT $accessToken';
    }
    return super.onRequest(options);
  }
}

class HttpLog extends Interceptor {
  @override
  Future onRequest(RequestOptions options) {
    print("\n ---------Start Http Request---------");
    print("Request_BaseUrl:${options.baseUrl}");
    print("Request_Path:${options.path}");
    print("Request_Method:${options.method}");
    print("Request_Headers:${options.headers}");
    print("Request_Data:${options.data}");
    print("Request_QueryParameters:${options.queryParameters}");
    print("---------End Http Request---------");
    return super.onRequest(options);
  }

  @override
  Future onResponse(Response response) {
    print("---------Start Http Response---------");
    print("Response_BaseUrl:${response.request.baseUrl}");
    print("Response_Path:${response.request.path}");
    print("Response_StatusCode:${response.statusCode}");
    print("Response_StatusMessage:${response.statusMessage}");
    print("Response_Headers:${response.headers.toString()}");
    print("---------End Http Response---------");
    return super.onResponse(response);
  }
}

class ErrorInterceptor extends Interceptor {
  @override
  onError(DioError error) async {
    print(error);
    //判读异常状态  401未登录过期或者未登录状态的异常
    if (error.response != null && error.response.statusCode == 401) {
      String token = await SharedPreferencesUtil.getData(Constants.ACCESS_TOKEN);//获取本地存储的Token
      if (token != null && token.trim() != '') {//Token存在则说明Token过期需要刷新，否则是未登录状态不做处理
        Dio dio = BaseNetWork.instance.dio;//获取应用的Dio对象进行锁定  防止后面请求还是未登录状态下请求
        dio.lock();
        String accessToken = await getToken();//重新获取Token
        dio.unlock();
        if (accessToken != '') {
          Dio tokenDio2 = new Dio(BaseNetWork.instance.dio.options); //创建新的Dio实例
          var request = error.request;
          request.headers['Authorization'] = 'JWT $accessToken';
          var response = await tokenDio2.request(request.path,
              data: request.data,
              queryParameters: request.queryParameters,
              cancelToken: request.cancelToken,
              options: request,
              onReceiveProgress: request.onReceiveProgress);
          return response;
        }
      }
    }
    super.onError(error);
  }

  Future<String> getToken() async {
    //获取当前的refreshToken，一般后台会在登录后附带一个刷新Token用的reToken
    String refreshToken =
        await SharedPreferencesUtil.getData(Constants.REFRESH_TOKEN);
    //因为App单例的Dio对象已被锁定，所以需要创建新的Dio实例
    Dio tokenDio = new Dio(BaseNetWork.instance.dio.options);
    Map<String, String> map = {
      "rft": refreshToken,
    }; //设置当前的refreshToken
    try {
      //发起请求，获取Token
      var response = await tokenDio.post("/api/v1/user/refresh_token", data: map);
      if (response.statusCode == 201) {
        LoginBean loginbean = LoginBean.fromJson(response.data);
        SharedPreferencesUtil.putData(Constants.ACCESS_TOKEN, loginbean.data.token);
        if (loginbean.data.rft != null && loginbean.data.rft.trim() != '') {
          SharedPreferencesUtil.putData(Constants.REFRESH_TOKEN, loginbean.data.rft);
        }
        return loginbean.data.token;
      }
      return '';
    } on DioError catch (e) {
      print("Token刷新失败:$e");
      SharedPreferencesUtil.putData(Constants.ACCESS_TOKEN, '');
      SharedPreferencesUtil.putData(Constants.REFRESH_TOKEN, '');
      return '';
    }
  }
}
